package com.senseuni.da.db

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.senseuni.da.MyApplication
import com.senseuni.da.db.dao.*
import com.senseuni.da.db.entity.*

@Database(entities = [UpgradeEntity::class, AppLogEntity::class, MediaEntity::class], version = 2, exportSchema = true)
abstract class AppDatabase :RoomDatabase(){

    companion object{
        @Volatile
        private var mAppDatabase: AppDatabase? = null

        // 使用双重检查锁定实现单例模式
        fun getInstance(): AppDatabase {
            return mAppDatabase ?: synchronized(this) {
                mAppDatabase ?: Room.databaseBuilder(
                    MyApplication.app.applicationContext,
                    AppDatabase::class.java, "lumx.db"
                )
                    .addMigrations(MIGRATION_1_2)
                    .allowMainThreadQueries()
                    .build().also { mAppDatabase = it }
            }
        }

        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                // Media 表新增 字段 duration
                database.execSQL("ALTER TABLE app_media ADD COLUMN hide INTEGER NOT NULL DEFAULT 0")
            }
        }
    }

    abstract fun upgradeDao(): UpgradeDao
    abstract fun appLogDao(): AppLogDao
    abstract fun mediaDao(): MediaDao

}